package uk.co.itmentor.pmff.parser;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.commons.lang.Validate;

import uk.co.itmentor.pmff.element.FFDocument;
import uk.co.itmentor.pmff.element.FFSection;
import uk.co.itmentor.pmff.handler.FFDocumentHandler;
/**
 * The serial parser for the flat file. 
 * Read data from flat file and generates events.
 * @author mdylag
 *
 * @param <D>
 */
public class FFEventParserImpl {
	/** An instance of the flat file document*/
	private FFDocument doc;
	/** A reference to the current section*/
	private FFSection currentSection;
	
	public FFEventParserImpl() 
	{
		
	}
	
	public void parse(FFDocument doc) throws FileNotFoundException, FFParserExcption
	{
		this.doc = doc;
		Validate.notNull(doc,"Document is null");
		Validate.notNull(doc.getFile(),"File is not defined in the document.");
		BufferedReader reader = new BufferedReader(new FileReader(doc.getFile()));
		parse(reader);
	}
	
	
	private void parse(BufferedReader reader) throws FFParserExcption
	{
		try {
			String line;
			while ((line=reader.readLine())!=null)
			{
				StringTokenizer tokenizer = new StringTokenizer(line,"\t");
				int column=0;
				String lines[] = new String[tokenizer.countTokens()];
				while (tokenizer.hasMoreTokens())
				{
					lines[column]=tokenizer.nextToken();
					column++;
				}
				if (lines.length!=0)
				{
					FFSection section=doc.getSectionByFieldName(lines[0]);
					if (section != null && (currentSection == null || currentSection != section) )
					{
						currentSection = section;
					}

					//process fields
					if (this.currentSection != null)
					{
						
						if (currentSection.isVertical())
						{
							System.out.println();
						}
						else
						{
							System.out.println();
						}
						//currentSection.g
					}
					
				}
			
			
			}
		} catch (IOException e) {
			throw new FFParserExcption("Problem with parse the file.",e);
			}
	}
	
}
